clear
insheet using "$sourcedatadir/wtid/view_cabinet.csv"
append  using "$gendatadir/view_cabinet_pres.dta"
drop if cabinet_party == 0

gen edate = date(election_date, "YMD")
format edate %td

gen cdate = date(start_date, "YMD")
format cdate %td

keep if prime_minister == 1
drop if caretaker == 1

sort country_name edate cdate
by country_name: gen pm_change = 1 if party_id != party_id[_n-1]
replace pm_change = 0 if pm_change == .

gen party_cab_start_date = .
replace party_cab_start_date = cdate if pm_change == 1
format party_cab_start_date  %td

bysort country_name: carryforward party_cab_start_date, gen(party_cab_start_date_x)

drop party_cab_start_date
rename  party_cab_start_date_x  party_cab_start_date

gen cum_pm_duration = (edate - party_cab_start_date)/365
// Where there was some time between an election and cabinet formation, this value can be negative.
// Reset those to zero.
replace cum_pm_duration = 0 if cum_pm_duration < 0

// But these 0-years-incumbency scores refer to the *new* party of the PM, not the party that was
// incumbent in the run-up to the election. So, replace those.
sort country_name edate
by country_name: replace cum_pm_duration = (edate - party_cab_start_date[_n-1])/365 if cum_pm_duration == 0

// Drop the between-election cabinet changes as we only care about cabinet durations at election times
sort country_name edate cdate
bysort country_name edate: drop if _n > 1

by country_name: gen incumbent_party_id = party_id[_n-1]
by country_name: gen incumbent_party    = party_name_short[_n-1]

keep country_name_short country_name country_id election_id cabinet_id edate pm_change cum_pm_duration incumbent_party_id incumbent_party

save "$gendatadir/party_pm_durations.dta", replace
